package commons.base.http.client;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.entity.ContentType;
import org.apache.http.util.EntityUtils;

public class Content {
    public static final Content NO_CONTENT = new Content(new byte[] {}, ContentType.DEFAULT_BINARY);
    
    public static Content get(HttpResponse response) throws UnsupportedCharsetException, ParseException, IOException{
    	int status = response.getStatusLine().getStatusCode();
		if (status >= 200 && status < 300) {
			HttpEntity entity = response.getEntity();
			return entity != null ? new Content(EntityUtils.toByteArray(entity), ContentType.get(entity)) : Content.NO_CONTENT;
		} else {
			throw new ClientProtocolException("Unexpected response status: " + status);
		}
    }

    private final byte[] raw;
    private final ContentType type;
    
    Content(final byte[] raw, final ContentType type) {
        super();
        this.raw = raw;
        this.type = type;
    }

    public ContentType getType() {
        return this.type;
    }

    public byte[] asBytes() {
        return this.raw.clone();
    }

    public String asString() {
        Charset charset = this.type.getCharset();
        if (charset == null) {
            charset = Consts.ISO_8859_1;
        }
        return asString(charset);
    }

    /**
     * @since 4.4
     */
    public String asString(final Charset charset) {
        return new String(this.raw, charset);
    }

    public InputStream asStream() {
        return new ByteArrayInputStream(this.raw);
    }

    @Override
    public String toString() {
        return asString();
    }
}
